package chatroom;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 客户端
 */
public class Client {
    private Socket socket=null;
    private String name=null;
    Client(){
        try {
            System.out.println("客户端正在连接...");
            socket=new Socket("localhost",9999);
            System.out.println("客户端连接成功！！！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void start(){
        //读取消息
        Du du = new Du(socket);
        Thread thread=new Thread(du);
        thread.start();

        try {
            //写入消息
            OutputStream outputStream = socket.getOutputStream();
            //转换流
            OutputStreamWriter osw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
            //缓冲流
            BufferedWriter bufferedWriter = new BufferedWriter(osw);
            //开启自动刷新，换行
            PrintWriter pw=new PrintWriter(bufferedWriter,true);
            Scanner sc=new Scanner(System.in);

            //输入昵称
            System.out.println("请输入昵称");
            name =sc.nextLine();
            pw.println(name);
            String message;
            while (true){
                message=sc.nextLine();
                if ("exit".equals(message)){
                    break;
                }
                pw.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //读取消息
     private class Du implements Runnable{
        private Socket socket;
        Du(){}
        Du(Socket socket){
            this.socket=socket;
        }

        @Override
        public void run() {
            try {
            InputStream is = socket.getInputStream();
            //转换流
            InputStreamReader inputStream1 = new InputStreamReader(is, StandardCharsets.UTF_8);
            //缓冲流
            BufferedReader br=new BufferedReader(inputStream1);

                String message;
                while (true){
                    if ((message=br.readLine())!=null){
                        System.out.println(message);
                    }

                }
            } catch (IOException e) {
                     e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

}
